import React, { useState, useRef, useEffect } from 'react';
import SvgIcon from '../Components/SvgIcon'
import axios from 'axios'
import mqtt from "mqtt";

const Voice = () => {

    const clientMqtt = useRef(null)
    const start = async () => {
        // initXiaozhi();
        // return;
        let opt = {
            "endpoint": "post-cn-apg3xckag01.mqtt.aliyuncs.com",
            "client_id": "GID_test@@@cd_62_f4_3d_b4_ba",
            "username": "Signature|LTAI5tF8J3CrdWmRiuTjxHbF|post-cn-apg3xckag01",
            "password": "ZniQJuMGL+eWdGdPqUBw/cYXPPA=",
            "publish_topic": "device-server",
            "subscribe_topic": "devices/cd_62_f4_3d_b4_ba"
        }
        const client = mqtt.connect(`mqtts://${opt.endpoint}:8883`,{        
            clientId: opt.client_id,
            username: opt.username, 
            password: opt.password,
            protocolVersion: 5, // 指定 MQTT 5.0
            rejectUnauthorized: false, // 要求服务器提供有效证书
            keepalive: 30,
        });
        // 连接成功回调
        client.on('connect', () => {
            console.log(`MQTT 连接成功`);
            // const subscribe_topic = opt['subscribe_topic'].split("/")[0] + '/p2p/GID_test@@@' + MAC_ADDR.replace(/:/g, '_')
            // console.log(`Connected to MQTT broker (MQTT 5.0):${subscribe_topic}`);
            client.subscribe(opt['subscribe_topic'], { qos: 2 }, (err) => {
                if (!err) {
                    console.log(`Subscribed to topic: ${opt['subscribe_topic']}`);
                } else {
                    console.error('Subscription error:', err);
                }
            });
        });

        // 接收消息回调
        client.on('message', (topic, message) => {
            console.log(`Received message on topic ${topic}: ${message.toString()}`);
        });

        // 错误处理
        client.on('error', (err) => {
            console.error('MQTT Error:', err);
        });

        // 连接关闭
        client.on('close', () => {
            console.log('Connection closed');
        });

        // 断开连接
        client.on('offline', () => {
            console.log('Client is offline');
        });
        // 创建 MQTT 客户端（使用 MQTT 5.0）
        // const client = mqtt.connect({
        //     host: 'post-cn-apg3xckag01.mqtt.aliyuncs.com',
        //     port: 8883,
        //     clientId: 'GID_test@@@28_37_2f_87_97_d0',
        //     username: 'Signature|LTAI5tF8J3CrdWmRiuTjxHbF|post-cn-apg3xckag01',
        //     password: 'Grwx1rLZBjF2PRUxU2EVTpWrAPw=',
        //     protocol: 'mqtts', // 使用 MQTT over TLS
        //     protocolVersion: '5.0', // 指定 MQTT 5.0
        //     rejectUnauthorized: true // 要求服务器提供有效证书
        // });

        // 连接成功回调
        client.on('connect', () => {
            console.log('Connected to MQTT broker (MQTT 5.0)');
            client.subscribe('your/topic', { qos: 1 }, (err) => {
                if (!err) {
                    console.log('Subscribed to topic: your/topic');
                } else {
                    console.error('Subscription error:', err);
                }
            });
        });

        // 接收消息回调
        client.on('message', (topic, message) => {
            console.log(`Received message on topic ${topic}: ${message.toString()}`);
        });

        // 错误处理
        client.on('error', (err) => {
            console.error('MQTT Error:', err);
        });

        // 连接关闭
        client.on('close', () => {
            console.log('Connection closed');
        });

        // 断开连接
        client.on('offline', () => {
            console.log('Client is offline');
        });
    }
    const initXiaozhi = async () => {
        console.log('SETP 1：页面初始化，请求服务器版本信息-------------')
        const resVersion = await get_ota_version();
        console.log(`SETP 2：请求服务器成功，返回值：`,resVersion)
        // 初始化键盘按下操作
        // initKeyPress();
        // 初始化MQTT
        // initMqtt(resVersion.mqtt);
        // 获取mqtt与版本信息
        // if (!clientMqtt.current) {
        //     
        //     await clientMqtt?.on("connect", () => {
        //         console.log('链接成功')
        //     });
        //     await  clientMqtt.current?.on('error', (error) => {
        //         clientMqtt.current?.end()
        //         console.log('链接失败')
        //     })
        // }
        
    }

    const get_ota_version = async () => {
        const MAC_ADDR = 'cd:62:f4:3d:b4:ba';//'28:37:2f:87:97:d0';
        const data = {
            "flash_size": 16777216, "minimum_free_heap_size": 8318916, "mac_address":MAC_ADDR,
            "chip_model_name": "esp32s3", "chip_info": {"model": 9, "cores": 2, "revision": 2, "features": 18},
            "application": {"name": "xiaozhi", "version": "0.9.9", "compile_time": "Jan 22 2025T20:40:23Z",
                        "idf_version": "v5.3.2-dirty",
                        "elf_sha256": "22986216df095587c42f8aeb06b239781c68ad8df80321e260556da7fcf5f522"},
            "partition_table": [{"label": "app","type": 1,"subtype": 2,"address": 0x10000,"size": 0x100000}],
            "ota": {"label": "factory"},
            "board": {"type": "bread-compact-wifi", "ssid": "mzy", "rssi": -58, "channel": 6,"ip": "192.168.124.38", "mac": MAC_ADDR}
        }
        const req = await axios({
            url: 'https://api.tenclass.net/xiaozhi/ota/',
            headers: {
                'Content-Type': 'application/json',
                'Device-Id': MAC_ADDR
            },
            method: 'post',//请求方法
            data: data,
        })
        return req.data;
    }
    const initMqtt = async (mqtt_info) => {
        // 客户端配置
        // const opt={
        //     host: mqtt_info.endpoint,
        //     port: 8883,
        //     clientId: mqtt_info.client_id,
        //     username: mqtt_info.username,
        //     password: mqtt_info.password,
        //     protocol: 'mqtts', // 使用 MQTT over TLS
        //     protocolVersion: 5, // 指定 MQTT 5.0
        //     rejectUnauthorized: false // 要求服务器提供有效证书
        // }
        // console.log(opt)
        // return;
        const client = mqtt.connect(`mqtts://${mqtt_info.endpoint}:8883`,{
            clientId: mqtt_info.client_id,
            username: mqtt_info.username,
            password: mqtt_info.password,
            protocolVersion: 5, // 指定 MQTT 5.0
        });
    
        // 连接成功事件
        client.on('connect', () => {
            console.log('Connected to MQTT broker');

            // 订阅主题
            client.subscribe('your/topic', (err) => {
                if (!err) {
                    console.log('Subscribed to topic: your/topic');
                } else {
                    console.error('Subscription error:', err);
                }
            });

            // 发布消息
            client.publish('your/topic', 'Hello MQTT', (err) => {
                if (!err) {
                    console.log('Message published');
                } else {
                    console.error('Publish error:', err);
                }
            });
        });

        // 接收消息事件
        client.on('message', (topic, message) => {
            console.log(`Received message on topic ${topic}: ${message.toString()}`);
        });

        // 连接错误事件
        client.on('error', (err) => {
            console.error('Connection error:', err);
        });

        // 连接关闭事件
        client.on('close', () => {
            console.log('Connection closed');
        });

        // 断开连接事件
        client.on('offline', () => {
            console.log('Client is offline');
        });
    }

    const [isSpeak, setIsSpeak] = useState(false);
    const initKeyPress = () => {
        document.addEventListener('keydown',(ev)=>{
            if(ev.code === 'Space' && !isSpeak){
                setIsSpeak(true)
            }
        })
        document.addEventListener('keyup',(ev)=>{
            if(ev.code === 'Space'){
                setIsSpeak(false)
            }
        })
    }
    useEffect(()=> {
       
    },[])
    return <div className="lk-room-container">
        <div className="fixed left-0 top-0 z-50 flex h-full w-full flex-col bg-token-main-surface-primary" style={{opacity: 1, willChange: 'auto'}}>
        <div className="relative h-full w-full" style={{opacity: 1, willChange: 'auto'}}><div className="flex h-full w-full flex-col justify-between gap-6" style={{opacity: 1, willChange: 'auto'}}>
            <div className="relative mt-6 flex w-full justify-center"><div className="flex w-full items-center justify-center"></div>
                <div className="mr-4">
                    <div className="relative h-[40px] w-[40px]">
                        <button className="btn relative btn-primary h-[40px] w-[40px] bg-transparent hover:bg-black/10 active:bg-black/20 dark:bg-transparent dark:hover:bg-white/5 dark:active:bg-white/10 h-16 w-16 overflow-hidden rounded-full border-none p-0.5 text-token-text-primary transition-colors duration-200 ease-in-out hover:text-token-text-secondary">
                            <div className="flex items-center justify-center">
                                <SvgIcon icon="option" width="22" height="22" viewBox="0 0 22 22" className="icon-md text-token-text-secondary" />
                            </div>
                        </button>
                    </div>
                </div>
            </div>
            <div className="flex h-full min-h-0 items-center justify-center">
                <div className="flex h-full w-full items-center justify-center" style={{opacity: 1, willChange: 'auto'}}>
                    <div className="flex items-center justify-center h-max min-h-bloop w-max min-w-bloop">
                        {/* <canvas width="227" height="227" style={{width: '227px', height: '227px'}}></canvas> */}
                        <div className={["voice",isSpeak?'voices_listen':''].join(' ')}></div>
                    </div>
                </div>
            </div>
            <div className="mb-6 flex justify-center">
                <div className="flex w-full flex-col items-center"><div className="relative mb-6 flex min-h-5 w-full items-center justify-center text-xs text-token-text-secondary">
                    <div style={{position: 'absolute', left: '50%', transform: 'translateX(-50%)',textAlign: 'center',pointerEvents: 'auto',cursor: 'pointer',opacity: 1, willChange: 'auto'}}>
                        <div className="flex items-center"></div>
                    </div>
                </div>
                    <div className="flex flex-row items-center gap-6 rounded-full px-3 py-1 transition-width duration-200 ease-in-out">
                        <span className="flex" data-state="closed"><span>
                            <button className="btn relative btn-primary bg-black/5 hover:bg-black/10 active:bg-black/20 dark:bg-[rgba(255,255,255,0.04)] dark:hover:bg-white/5 dark:active:bg-white/10 h-16 w-16 overflow-hidden rounded-full border-none p-0.5 text-token-text-primary transition-colors duration-200 ease-in-out hover:text-token-text-secondary" aria-label="关闭麦克风">
                                <div className="flex items-center justify-center">
                                    <SvgIcon icon={isSpeak?"speak":'play'} fill="currentColor" className="icon-xl text-token-main-surface-primary-inverse"/> 
                                   {/* <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="icon-xl text-danger"><path d="M7.5 8.91422V10.5C7.5 12.9853 9.51472 15 12 15C12.4787 15 12.9399 14.9253 13.3726 14.7868L14.5285 15.9427C13.7599 16.3004 12.9031 16.5 11.9999 16.5C9.28338 16.5 6.98608 14.6939 6.24825 12.2148C6.09071 11.6854 5.53389 11.384 5.00455 11.5415C4.47521 11.6991 4.17381 12.2559 4.33134 12.7852C5.22277 15.7805 7.82091 18.0418 11 18.4381V19.5H9.5C8.94772 19.5 8.5 19.9477 8.5 20.5C8.5 21.0523 8.94772 21.5 9.5 21.5H14.5C15.0523 21.5 15.5 21.0523 15.5 20.5C15.5 19.9477 15.0523 19.5 14.5 19.5H13V18.4381C14.086 18.3027 15.1043 17.9496 16.0098 17.424L19.2929 20.7071C19.6834 21.0976 20.3166 21.0976 20.7071 20.7071C21.0976 20.3166 21.0976 19.6834 20.7071 19.2929L4.70711 3.29289C4.31658 2.90237 3.68342 2.90237 3.29289 3.29289C2.90237 3.68342 2.90237 4.31658 3.29289 4.70711L7.5 8.91422Z" fill="currentColor"></path><path d="M17.3874 13.1448L18.8601 14.6174C19.202 14.0488 19.4753 13.4343 19.6685 12.7852C19.826 12.2559 19.5246 11.6991 18.9953 11.5415C18.466 11.384 17.9091 11.6854 17.7516 12.2148C17.6557 12.537 17.5335 12.8478 17.3874 13.1448Z" fill="currentColor"></path><path d="M8.46182 4.21918L16.2436 12.001C16.4096 11.5315 16.5 11.0263 16.5 10.5V7C16.5 4.51472 14.4853 2.5 12 2.5C10.5644 2.5 9.28577 3.17227 8.46182 4.21918Z" fill="currentColor"></path></svg> */}
                                </div>
                            </button>
                        </span>
                        </span>
                        <span className="flex" data-state="closed"><span>
                            <button className="btn relative btn-primary bg-black/5 hover:bg-black/10 active:bg-black/20 dark:bg-[rgba(255,255,255,0.04)] dark:hover:bg-white/5 dark:active:bg-white/10 h-16 w-16 overflow-hidden rounded-full border-none p-0.5 text-token-text-primary transition-colors duration-200 ease-in-out hover:text-token-text-secondary" aria-label="结束语音模式">
                                <div className="flex items-center justify-center" onClick={start}>
                                    <SvgIcon icon="stop" width="29" height="28" viewBox="0 0 29 28" className="icon-xl text-token-main-surface-primary-inverse" />
                                </div>
                            </button>
                        </span></span>
                    </div>
                </div>
            </div>
        </div>
            <div className="absolute bottom-0 right-0 flex w-auto items-center justify-end p-4" style={{opacity: 1, willChange: 'auto'}}></div>
        </div>
    </div>
        <div style={{display: 'none'}}>
            <audio className="lk-participant-media-audio" data-lk-local-participant="false" data-lk-source="microphone" autoPlay=""></audio>
            <audio className="lk-participant-media-audio" data-lk-local-participant="false" data-lk-source="microphone" autoPlay=""></audio>
            <audio className="lk-participant-media-audio" data-lk-local-participant="false" data-lk-source="microphone" autoPlay=""></audio>
        </div>
    </div>;
};

export default Voice;